﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;
using HotelManageSystem.Domain;
using HotelManageSystem.Domain.Entities;
using HotelManageSystem.Domain.Infrastructure;
using HotelManageSystem.Models;
using Telerik.Web.Mvc;

namespace HotelManageSystem.Controllers
{
    public class DeliveryorderController : Controller
    {
        //
        // GET: /Deliveryorder/
        private readonly IProductRepository _productRepository;
        private readonly IUnitOfWork _unitOfWork;
        private readonly IDeliveryorderRepository _deliveryorderRepository;
        private readonly IInventoryRepository _inventoryRepository;
        private readonly IEmployeeRepository _employeeRepository;
        private readonly IProductDetailOutRepository _productDetailOutRepository;
        public DeliveryorderController(IProductDetailOutRepository productDetailOutRepository,IEmployeeRepository employeeRepository, IDeliveryorderRepository deliveryorderRepository, IUnitOfWork unitOfWork, IProductRepository productRepository, IInventoryRepository inventoryRepository)
        {
            _deliveryorderRepository = deliveryorderRepository;
            _inventoryRepository = inventoryRepository;
            _productRepository = productRepository;
            _employeeRepository = employeeRepository;
            _productDetailOutRepository = productDetailOutRepository;
            _unitOfWork = unitOfWork;
        }

        private IList<DeliveryorderModel> GetAllDeliveryorderModels()
        {
            var deliveryorder = _deliveryorderRepository.GetAll().AsQueryable();
            IList<DeliveryorderModel> deliveryorderModels =
                         (from d in deliveryorder
                          select new DeliveryorderModel
                          {
                              ID = d.ID,
                              DeliveryorderID = d.DeliveryorderID,
                              Outprice = d.Outprice,
                              time = d.time,
                              Count = d.Count,
                              Product = d.Product.Name,
                              Total = d.Total,
                              Billproducer = d.Billproducer,
                              Employee = d.Employee.Name
                          }
                     ).ToList();
            return deliveryorderModels;
        }

        [GridAction]
        public ActionResult TelerikAjax()
        {
            ViewData["products"] = _productRepository.GetAll();
            ViewData["employees"] = _employeeRepository.GetAll();
            return View(new GridModel(GetAllDeliveryorderModels()));
        }

        public ActionResult Index(string sortMember, int? currentPage)
        {
            ViewData["products"] = _productRepository.GetAll();
            ViewData["employees"] = _employeeRepository.GetAll();
            ViewData["sortMember"] = sortMember ?? "ID";
            //分页
            ViewData["currentPage"] = currentPage ?? 1;//当前页
            return View(GetAllDeliveryorderModels());
        }
        public ActionResult Creat(Deliveryorder deliveryorder)
        {
            var productName = _productRepository.GetAll();
            ViewData["productName"] = new SelectList(productName, "ID", "Name");
            var employeeName = _employeeRepository.GetAll();
            ViewData["employee"] = new SelectList(employeeName, "ID", "Name");
            ViewData["DeliveryorderID"] = "DELIVERYORDERID" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day +
                                       DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second;
            if(Request.HttpMethod=="POST")
            {
                deliveryorder.DeliveryorderID = ViewData["DeliveryorderID"].ToString();
                deliveryorder.Outprice = Convert.ToInt32(Request.Form["Outprice"]);
                deliveryorder.Count = Convert.ToInt32(Request.Form["textcount"]);
                deliveryorder.Total = Convert.ToInt32(Request.Form["texttotal"]);
                var productID = Request["productName"];
                deliveryorder.Product = _productRepository.Get(p=>p.ID==Convert.ToInt32(productID));
                var employeeID = Request["employee"];
                deliveryorder.Employee = _employeeRepository.Get(e => e.ID == Convert.ToInt32(employeeID));
                //插入货品的明细编号，出库单价，出库数量
                var productdetailOut = new ProductDetailOut
                                           {
                                               DetailNumberOut =
                                                   "PRODUCTOUT" + DateTime.Now.Year + DateTime.Now.Month +
                                                   DateTime.Now.Day +
                                                   DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second,
                                               Product = deliveryorder.Product,
                                               OutPrice = deliveryorder.Outprice,
                                               Count1 = deliveryorder.Count,
                                               Total = deliveryorder.Total
                                           };
                _productDetailOutRepository.Add(productdetailOut);
                _unitOfWork.Commit();
                deliveryorder.ProductDetailIOut = _productDetailOutRepository.Get(x=>x.ID==productdetailOut.ID);
                _deliveryorderRepository.Add(deliveryorder);
                _unitOfWork.Commit();
                //获取出库时货品的ID
                var productid = deliveryorder.Product.ID;
                //获取库存的所有信息
                var inventory = _inventoryRepository.Get(i=>i.Product.ID==productid);
                if(inventory!=null)
                {
                    inventory.Count -= deliveryorder.Count;
                    _inventoryRepository.Update(inventory);
                    _unitOfWork.Commit();
                }
                //修改货品信息
                var product = _productRepository.Get(x => x.ID == deliveryorder.Product.ID);
                product.PriceOut = deliveryorder.Outprice;
                product.Count += deliveryorder.Count;
                _productRepository.Update(product);
                _unitOfWork.Commit();
                return RedirectToAction("Index");
            }
            return View();
        }
        //根据货品的ID查询货品的库存数量
        public JsonResult GetInventory(int productNameid)
        {
            var inventory = _inventoryRepository.Get(x => x.Product.ID == productNameid);
            if(inventory!=null)
            {
                return Json(inventory.Count, JsonRequestBehavior.AllowGet);
            }
            return Json(0,JsonRequestBehavior.AllowGet);
        }
        public ActionResult Edit(int id)
        {
             //使用出库单的ID检索
            var deliveryorder = _deliveryorderRepository.GetById(id);
            //保存出库单在未修改前货品的数量
            var outcount = deliveryorder.Count;
            var pID = deliveryorder.Product.ID;
            //货品出库未修改前的数量
            var beginCount = deliveryorder.Count;
           switch (Request.HttpMethod)
           {
               case "POST":
                   {
                       deliveryorder.Outprice = Convert.ToDecimal(Request.Form["Outprice"]);
                       deliveryorder.Count = Convert.ToInt32(Request.Form["textcount"]);
                       deliveryorder.Total = Convert.ToDecimal(Request.Form["texttotal"]);
                       deliveryorder.Product = _productRepository.Get(p => p.ID == Convert.ToInt32(Request["productName"]));
                       deliveryorder.Employee = _employeeRepository.Get(e => e.ID == Convert.ToInt32(Request["employee"]));
                       
                       if (TryUpdateModel(deliveryorder, null, null, new[] { "productName", "employee" }))
                       {
                           _deliveryorderRepository.Update(deliveryorder);
                           _unitOfWork.Commit();
                       }
                       var productDetailOut = _productDetailOutRepository.Get(x => x.ID == deliveryorder.ProductDetailIOut.ID);
                       productDetailOut.OutPrice = deliveryorder.Outprice;
                       productDetailOut.Count1 = deliveryorder.Count;
                       productDetailOut.Total = deliveryorder.Total;
                       productDetailOut.Product = deliveryorder.Product;
                       productDetailOut.DetailNumberOut = "PRODUCTOUT" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day +
                                                          DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second;
                       //出货明细更新
                       _productDetailOutRepository.Update(productDetailOut);
                       _unitOfWork.Commit();
                       //获取入库时的货品ID
                       var productid = deliveryorder.Product.ID;
                       //判断在出库单修改的时候，用户是否修改了货品名
                       if(pID==productid)
                       {
                           //获取更新后的出库单
                           var de = _deliveryorderRepository.Get(d=>d.Product.ID==productid);
                           //获取库存的所有信息
                           var inventory = _inventoryRepository.Get(i => i.Product.ID == productid);
                           if(de.Count>=outcount)
                           {
                               var result = de.Count - outcount;
                               inventory.Count -= result;
                               _inventoryRepository.Update(inventory);
                               _unitOfWork.Commit();
                           }
                           else
                           {
                               var result = outcount - de.Count;
                               inventory.Count += result;
                               _inventoryRepository.Update(inventory);
                               _unitOfWork.Commit();
                           }
                           //修改货品信息
                           var product = _productRepository.Get(x => x.ID == deliveryorder.Product.ID);
                           product.PriceOut = deliveryorder.Outprice;
                           //判断出库时修改出库信息，修改货品出库后的剩余量
                           //出库单修改前的出库数量
                           
                           //出库单修改后的数量
                           var endCount = de.Count;
                           if(beginCount>=endCount)
                           {
                               product.Count -= beginCount - endCount;
                               _productRepository.Update(product);
                               _unitOfWork.Commit();
                           }
                           else
                           {
                               product.Count += endCount - beginCount;
                               _productRepository.Update(product);
                               _unitOfWork.Commit();
                           }
                       }
                       else
                       {
                           //更新后的出库单的ID
                           var de = _deliveryorderRepository.GetById(id);
                           //获取库存信息
                           var inventory = _inventoryRepository.Get(i=>i.Product.ID==de.Product.ID);
                           if (de.Count >= outcount)
                           {
                               var result = de.Count - outcount;
                               inventory.Count -= result;
                               _inventoryRepository.Update(inventory);
                               _unitOfWork.Commit();
                           }
                           else
                           {
                               var result = outcount - de.Count;
                               inventory.Count += result;
                               _inventoryRepository.Update(inventory);
                               _unitOfWork.Commit();
                           }
                       }
                       return RedirectToAction("Index");
                   }
               default:
                   ViewData["productName"] = new SelectList(_productRepository.GetAll(), "ID", "Name", deliveryorder.Product.ID);
                   ViewData["employee"] = new SelectList(_employeeRepository.GetAll(), "ID", "Name", deliveryorder.Employee.ID);
                   ViewData["Outprice"] = deliveryorder.Outprice;
                   ViewData["textcount"] = deliveryorder.Count;
                   ViewData["texttotal"] = deliveryorder.Total;
                   return View(deliveryorder);
           }
        }

        [HttpPost]
        [GridAction]
        public ActionResult Delete(int id)
        {
            var deliveryorder = _deliveryorderRepository.GetById(id);
            var productDetailOut = _productDetailOutRepository.Get(x=>x.ID==Convert.ToInt32(deliveryorder.ProductDetailIOut.ID));
           //删除出库单时库存应当增加出库时的数量
            var inventory = _inventoryRepository.Get(x => x.Product.ID == Convert.ToInt32(deliveryorder.Product.ID));
            inventory.Count += deliveryorder.Count;
            _inventoryRepository.Update(inventory);
            _unitOfWork.Commit();
            _productDetailOutRepository.Delete(productDetailOut);
            _unitOfWork.Commit();
            var product = _productRepository.Get(x=>x.ID==_deliveryorderRepository.GetById(id).Product.ID);
            product.Count -= _deliveryorderRepository.GetById(id).Count;
            _productRepository.Update(product);
            _unitOfWork.Commit();
            if(TryUpdateModel(deliveryorder))
            {
                _deliveryorderRepository.Delete(deliveryorder);
                _unitOfWork.Commit();
                return View(new GridModel(GetAllDeliveryorderModels()));
            }
            return View();
        }

    }
}
